<template>
	<view>
		<view class="info_box pdl-36 pdr-36">
			<view class="info_title flex-col">
				<view class="title fs42">信息填写</view>
				<text class="desc mgt-19 fs22">填写个人信息即可快速审核放款</text>
			</view>
			<view class="info_container mgt-49">
				<!-- 基本信息 -->
				<view class="base_box">
					<view class="flex-ac common_top pdt-22 pdb-22 pdl-17 pdr-17">
						<image class="common_img" src="/static/src/authentication/base_icon.png" mode="aspectFit">
						</image>
						<text class="common_title fs30 mgl-16">基本信息</text>
					</view>
					<view class="common_wrap pdl-30 pdr-30">
						<u-form :model="baseForm" ref="formRef" :error-type="errorType" label-width="180"
							:label-style="baseLabelStyle">
							<u-form-item label="婚姻状态" prop="maritalStatus">
								<view class="flex1 flex-ac flex-sb" @click="handleShow(1)">
									<view :class="baseForm.maritalStatus?'':'default'">
										{{baseForm.maritalStatus?baseForm.maritalStatus:'请选择婚姻状况'}}
									</view>
									<view class="df">
										<u-icon name="arrow-right" color="#666666" size="26"></u-icon>
									</view>
								</view>
							</u-form-item>
							<u-form-item label="教育程度" prop="educate">
								<view class="flex1 flex-ac flex-sb" @click="handleShow(2)">
									<view :class="baseForm.educate?'':'default'">
										{{baseForm.educate?baseForm.educate:'请选择教育程度'}}
									</view>
									<view class="df">
										<u-icon name="arrow-right" color="#666666" size="26"></u-icon>
									</view>
								</view>
							</u-form-item>
							<u-form-item label="现居地址" prop="residentialAddress">
								<view class="flex1 flex-ac flex-sb" @click="handleShow(3)">
									<view class="u-overflow-1 flex1" :class="baseForm.residentialAddress?'':'default'">
										{{baseForm.residentialAddress?baseForm.residentialAddress:'请选择现居地址'}}
									</view>
									<view class="df">
										<u-icon name="arrow-right" color="#666666" size="26"></u-icon>
									</view>
								</view>
							</u-form-item>
							<u-form-item label="详细地址" prop="fullAddress">
								<u-input @blur="handleInput($event,1)" type="text" v-model="baseForm.fullAddress"
									height="65" placeholder="请填写详细地址" clearable maxlength="120" showWordLimit />
							</u-form-item>
						</u-form>
					</view>
				</view>
				<!--公司联系人 -->
				<view class="company_box mgt-40">
					<view class="flex-ac common_top pdt-22 pdb-22 pdl-17 pdr-17">
						<image class="common_img" src="/static/src/authentication/company_icon.png" mode="aspectFit">
						</image>
						<text class="common_title fs30 mgl-16">公司信息</text>
					</view>
					<u-form :model="companyForm" ref="formRef2" :error-type="errorType" label-width="180"
						:label-style="baseLabelStyle">
						<view class="common_wrap pdl-30 pdr-30">
							<u-form-item label="公司名称" prop="companyName">
								<u-input @blur="handleInput($event,2)" type="text" v-model="companyForm.companyName"
									height="65" placeholder="请填写公司名称" clearable maxlength="120" showWordLimit />
							</u-form-item>
							<u-form-item label="年收入" prop="workIncome">
								<u-input @blur="handleInput($event,3)" type="number" v-model="companyForm.workIncome"
									height="65" placeholder="请填写年收入" clearable maxlength="20" showWordLimit />
							</u-form-item>
							<u-form-item label="所属行业" prop="workIndustry">
								<view class="flex1 flex-ac flex-sb" @click="handleShow(4)">
									<view :class="companyForm.workIndustry?'':'default'">
										{{companyForm.workIndustry?companyForm.workIndustry:'请选择所属行业'}}
									</view>
									<view class="df">
										<u-icon name="arrow-right" color="#666666" size="26"></u-icon>
									</view>
								</view>
							</u-form-item>
						</view>
					</u-form>
				</view>
				<!-- 联系人 -->
				<view class="contact_box mgt-40">
					<view class="flex-ac common_top pdt-22 pdb-22 pdl-17 pdr-17">
						<image class="common_img" src="/static/src/authentication/contact_icon.png" mode="aspectFit">
						</image>
						<text class="common_title fs30 mgl-16">联系人</text>
					</view>
					<u-form :model="contactForm" ref="formRef3" :error-type="errorType" :label-style="baseLabelStyle"
						label-width="180">
						<view class="common_wrap pdt-30" v-for="(item,index) in contactForm" :key="index">
							<view class="pdl-30 pdr-30">
								<view class="title pdl-4 pdb-24 fs28">
									{{ index === 0 ? '常用联系人' : '其他联系人' }}
								</view>
								<view class="flex-ac " v-if="index===0">
									<!-- tagCurrent -->
									<view :class="tagCurrent=== v.value?'contact_tag active_tag':''"
										class="contact_tag pdt-12 pdl-28 pdr-28 pdb-8 fs24 mgl-20"
										v-for="(v,i) in theTopThreeContacts" :key="i" @click="handleTag(i,1,v.value)">
										{{v.label}}
										<image v-if="tagCurrent===v.value" class="contact_tag_img"
											src="/static/src/authentication/tag_active_icon.png" mode="aspectFill">
										</image>
									</view>
								</view>

								<view class="flex-ac " v-if="index===1">
									<view :class="tagCurrent2===v.value?'contact_tag active_tag':''"
										class="contact_tag pdt-12 pdl-28 pdr-28 pdb-8 fs24 mgl-20"
										v-for="(v,i) in theLastThreeContacts" :key="i" @click="handleTag(i,2,v.value)">
										{{v.label}}
										<image v-if="tagCurrent2===v.value" class="contact_tag_img"
											src="/static/src/authentication/tag_active_icon.png" mode="aspectFill">
										</image>
									</view>
								</view>
							</view>
							<view class="w100 telephone_directory flex-ac pdl-30 pdr-20">
								<view class="left">
									<u-form-item label="联系人姓名" :prop="`${index}.fullName`">
										<u-input @blur="handleName($event,index)" type="text" v-model="item.fullName"
											height="65" placeholder="请填写联系人姓名" clearable maxlength="20" showWordLimit />
									</u-form-item>
									<u-form-item label="手机号码" :prop="`${index}.mobile`" :border-bottom="false">
										<u-input @blur="handleTel($event,index)" type="number" v-model="item.mobile"
											height="65" placeholder="请填写手机号码" clearable maxlength="11" showWordLimit />
									</u-form-item>
								</view>
								<!-- #ifdef APP-PLUS -->
								<view class="flex-ac flex-col select_contacts fs22 flex1" @click="handleContacts">
									<img class="select_book_img" src="/static/src/authentication/address_book_icon.png"
										mode="aspectFit">
									<text class="mgt-16">选择联系人</text>
								</view>
								<!-- #endif -->
							</view>
						</view>
					</u-form>
				</view>
				<u-button class="back_btn mgt-62 fs32" shape="circle" :hair-line="false" :ripple="true"
					throttle-time="2000" @click="handleBack">上一步</u-button>
				<u-button class="next_btn mgt-24 fs32" shape="circle" :ripple="true" throttle-time="2000"
					@click="handleNext">下一步</u-button>

				<!-- 单列 -->
				<u-select :default-value="[getCurrentIndex]" v-model="showSelect" :safe-area-inset-bottom="true"
					mode="single-column" :list="list" label-name="dictLabel" value-name="dictValue"
					@confirm="handConfim"></u-select>
				<!-- 多列地区 -->
				<u-select v-model="showArea" mode="mutil-column-auto" :list="areaList" label-name="label"
					value-name="value" child-name="children" @confirm="selectConfim"></u-select>
			</view>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { useInformation } from '@/store/modules/index.ts'

	import { computed, onMounted, ref } from 'vue';

	import type { baseItem, dictItem, maritalItem, areaItem, addressItem, companyItem, telephoneItem, baseInfoRules, companyRules, concatRules, dictConcatItem, contactItem } from "../../../static/src/types/step"

	import { getDict, getTree } from "@/api/dict";

	// #ifdef APP-PLUS
	import { nativeContact } from "../../../utils/nativeContact.js"
	// #endif

	const user = useInformation()

	defineProps({
		currentNum: {
			type: Number,
			default: 0
		}
	})
	const errorType = ref(['message'])
	const baseForm = ref<baseItem>({
		maritalStatus: "",
		maritalValue:"",
		educate: "",
		educateValue:"",
		province: "",
		city: "",
		area: "",
		residentialAddress: "",
		fullAddress: ""
	})
	const companyForm = ref<companyItem>({
		companyName: "",
		workIncome: "",
		workIndustry: "",
		workIndustryValue:""
	})
	const contactList = ref<contactItem[]>([])

	const contactForm = ref<telephoneItem[]>(
		[
			{
				fullName: "",
				mobile: "",
				relation: ""
			},
			{
				fullName: "",
				mobile: "",
				relation: ""
			}
		]
	)

	const tagCurrent = ref<string>("0")
	const tagCurrent2 = ref<string>("0")

	const currentType = ref<number>(0)
	const currentSelectType = ref<string>('');
	const defaultValue = ref<number[]>([0])
	const maritalStatusIndex = ref<number>(0);
	const educateIndex = ref<number>(0);
	const industryIndex = ref<number>(0)
	const formRef = ref<any>(null);
	const formRef2 = ref<any>(null);
	const formRef3 = ref<any>(null);
	const rules = ref<baseInfoRules>({
		maritalStatus: [{ required: true, message: "请选择婚姻状况", trigger: ['change', 'blur'] },],
		educate: [{ required: true, message: "请选择教育程度", trigger: ['change', 'blur'] }],
		residentialAddress: [{ required: true, message: "请选择现居地址", trigger: ['change', 'blur'] }],
		fullAddress: [{ required: true, message: "请填写详细地址", trigger: ['change', 'blur'] }],
	});

	const rules2 = ref<companyRules>({
		companyName: [{ required: true, message: "请填写公司名称", trigger: ['change', 'blur'] }],
		workIncome: [{ required: true, message: "请选择所属行业", trigger: ['change', 'blur'] }],
	});

	const rules3 = ref<concatRules>({
	  '0.fullName': [
	    { required: true, message: "请输入真实姓名", trigger: ['change', 'blur'] },
	    { pattern: /^[\u4E00-\u9FA5]+$/, message: "只能输入汉字" }
	  ],
	  '0.mobile': [
	    { required: true, message: "请填写手机号码", trigger: ['change', 'blur'] },
		{ pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确" }
	  ],
	  '1.fullName': [
	    { required: true, message: "请输入真实姓名", trigger: ['change', 'blur'] },
	    { pattern: /^[\u4E00-\u9FA5]+$/, message: "只能输入汉字" }
	  ],
	  '1.mobile': [
	    { required: true, message: "请填写手机号码", trigger: ['change', 'blur'] },
		{ pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确" }
	  ]
	});




	const baseLabelStyle = {
		color: '#5A5B66',
		fontFamily: ' PingFang SC',
		fontWeight: '500',
		fontSize: '28rpx'
	}
	const showSelect = ref<boolean>(false)
	const showArea = ref<boolean>(false)
	const list = ref<{ dictValue : string, dictLabel : string }[]>([]);
	const areaList = ref([[], [], []])

	const emit = defineEmits<{
		(e : 'handleCurrent', data : number) : void;
	}>();

	// 计算当前应该使用的默认索引
	const getCurrentIndex = computed(() => {
		switch (currentType.value) {
			case 1:
				return maritalStatusIndex.value;
			case 2:
				return educateIndex.value;
			case 4:
				return industryIndex.value;
			default:
				return 0;
		}
	})
	const theTopThreeContacts = computed<contactItem[]>(() => contactList.value.slice(0, 3));
	const theLastThreeContacts = computed<contactItem[]>(() => contactList.value.slice(3, 6));

	// 获取联系人字典
	const handleContactDict = async () => {      
		const currentIdentity = user.getIdentity()
		let res = await getDict('lo_contact_relationship')
		if (res) {
			contactList.value = res.data.map((item : dictConcatItem) => ({
				label: item.dictLabel,
				value: item.dictValue,
			}))

			const newRelationships : telephoneItem[] = [
				{
					fullName: currentIdentity.relationships?.[0]?.fullName || '',
					mobile: currentIdentity.relationships?.[0]?.mobile || '',
					relation: currentIdentity.relationships?.[0]?.relation || theTopThreeContacts.value[0]?.value
				},
				{
					fullName: currentIdentity.relationships?.[1]?.fullName || '',
					mobile: currentIdentity.relationships?.[1]?.mobile || '',
					relation: currentIdentity.relationships?.[1]?.relation || theLastThreeContacts.value[0]?.value
				}
			];

			user.setIdentity({
				...currentIdentity,
				relationships: newRelationships
			});
		}
	}
	
	const handleShow = async (type : number) => {
		// 根据type确定当前选择的类型
		currentType.value = type
		switch (currentType.value) {
			case 1:
				currentSelectType.value = 'lo_marital_status';
				await loadDictData(currentSelectType.value);
				break;
			case 2:
				currentSelectType.value = 'lo_educational_level';
				await loadDictData(currentSelectType.value);
				break;
			case 3:
				await loadTree();
				break;
			case 4:
				currentSelectType.value = 'lo_industry';
				await loadDictData(currentSelectType.value);
				break;
		}
	};
	// 加载对应字典数据
	const loadDictData = async (value : string) => {
		let res = await getDict(value)
		if (res) {
			list.value = res.data
			showSelect.value = true;
		}
		return
	}
	//加载树结构
	const loadTree = async () => {
		let res = await getTree()
		if (res) {
			console.log(res, 'res')
			areaList.value = res.data.map((item : areaItem) => ({
				label: item.label,
				value: item.id,
				children: item.children?.map((child : areaItem) => ({
					label: child.label,
					value: child.id,
					children: child.children?.map((grandChild : areaItem) => ({
						label: grandChild.label,
						value: grandChild.id
					}))
				}))
			}));
			showArea.value = true
		}
	}
	const handConfim = (e : maritalItem[]) => {
		const currentIdentity = user.getIdentity()
		if (currentType.value === 1) {
			baseForm.value.maritalStatus = e[0].label
			baseForm.value.maritalValue = e[0].value
			maritalStatusIndex.value = list.value.findIndex(item => item.dictValue === e[0].value);
			user.setIdentity({
				...currentIdentity,
				maritalStatus: baseForm.value.maritalStatus,
				maritalValue: baseForm.value.maritalValue,
			});
		}
		if (currentType.value === 2) {
			baseForm.value.educate = e[0].label
			baseForm.value.educateValue = e[0].value
			educateIndex.value = list.value.findIndex(item => item.dictValue === e[0].value);
			user.setIdentity({
				...currentIdentity,
				educate: baseForm.value.educate,
				educateValue:baseForm.value.educateValue
			});
		}
		if (currentType.value === 4) {
			companyForm.value.workIndustry = e[0].label
			companyForm.value.workIndustryValue = e[0].value
			industryIndex.value = list.value.findIndex(item => item.dictValue === e[0].value);
			user.setIdentity({
				...currentIdentity,
				workIndustry: companyForm.value.workIndustry,
				workIndustryValue:companyForm.value.workIndustryValue
			});
		}
	}
	const selectConfim = (e : addressItem[]) => {
		const currentIdentity = user.getIdentity()
		const [province, city, area] = e;
		baseForm.value = {
			...baseForm.value, // 保留其他字段
			province: province.label,
			city: city.label,
			area: area.label,
			residentialAddress: `${province.label}${city.label}${area.label}`
		};
		user.setIdentity({
			...currentIdentity,
			...baseForm.value,
		});
	}
	const handleTag = (i : number, num : number, value : string) => {
		const currentIdentity = user.getIdentity();
		const newRelationships = [...currentIdentity.relationships];
		if (num === 1) {
			tagCurrent.value = value; // 更新 tagCurrent.value
			newRelationships[0] = {
				...newRelationships[0],
				relation: value,
			};
		} else if (num === 2) {
			tagCurrent2.value = value; // 更新 tagCurrent2.value
			newRelationships[1] = {
				...newRelationships[1],
				relation: value,
			};
		}

		user.setIdentity({
			...currentIdentity,
			relationships: newRelationships,
		});
	};
	// #ifdef APP-PLUS
	// const handleContacts = async () => {
	// 	const systemInfo = uni.getSystemInfoSync();
	// 	if (systemInfo.platform === 'android') {
	// 		nativeContact.contacts.getContact(function (name : string, phoneNumber : string) {
	// 			contactForm.value={
	// 				fullName: name,
	// 				mobile: phoneNumber,
	// 			}
	// 		})
	// 	}
	// }
	// #endif

	const handleInput = (e : string, num : number) => {
		const currentIdentity = user.getIdentity();
		switch (num) {
			case 1:
				user.setIdentity({ ...currentIdentity, fullAddress: e });
				break;
			case 2:
				user.setIdentity({ ...currentIdentity, companyName: e });
				break;
			case 3:
				user.setIdentity({ ...currentIdentity, workIncome: e });
				break;
		}
	}

	const handleName = (e : string, i : number) => {
		const currentIdentity = user.getIdentity();
		if (i === 0) {
			contactForm.value[0].fullName = e;
		} else if (i === 1) {
			contactForm.value[1].fullName = e;
		}

		user.setIdentity({
			...currentIdentity,
			relationships: [
				{
					fullName: contactForm.value[0].fullName,
					mobile: currentIdentity.relationships?.[0]?.mobile || '',
					relation: currentIdentity.relationships[0].relation,
				},
				{
					fullName: contactForm.value[1].fullName,
					mobile: currentIdentity.relationships?.[1]?.mobile || '',
					relation: currentIdentity.relationships[1].relation,
				},
			],
		});
	};
	const handleTel = (e : string, i : number) => {
		const currentIdentity = user.getIdentity();
		if (i === 0) {
			contactForm.value[0].mobile = e;
		} else if (i === 1) {
			contactForm.value[1].mobile = e;
		}

		user.setIdentity({
			...currentIdentity,
			relationships: [
				{
					fullName: contactForm.value[0].fullName,
					mobile: contactForm.value[0].mobile || '',
					relation: currentIdentity.relationships[0].relation,
				},
				{
					fullName: contactForm.value[1].fullName,
					mobile: contactForm.value[1].mobile || '',
					relation: currentIdentity.relationships[1].relation,
				},
			],
		});
	};

	const handleBack = () => {
		emit('handleCurrent', 1);
		uni.pageScrollTo({
			scrollTop: 0,
			duration: 300
		});
	}


	const handleNext = async () => {
		try {
			// 使用Promise.all等待所有验证完成
			const [valid1, valid2, valid3] = await Promise.all([
				formRef.value.validate(),
				formRef2.value.validate(),
				formRef3.value.validate()
			]);

			if (!valid1 || !valid2 || !valid3) {
				const message = !valid1 ? "请检查基本信息是否完整" :
					!valid2 ? "请检查公司信息是否完整" :
						"请检查联系人信息是否完整";
				uni.showToast({ icon: "none", title: message });
				return;
			}
			// 验证通过后跳转
			emit('handleCurrent', 3);
			uni.pageScrollTo({
				scrollTop: 0,
				duration: 300
			});
		} catch (error) {
			console.error('验证出错:', error);
			uni.showToast({ icon: "none", title: "验证过程中出错" });
		}
	};
	onMounted(() => {
		const currentIdentity = user.getIdentity();
		handleContactDict()
		formRef.value.setRules(rules.value);
		formRef2.value.setRules(rules2.value);
		formRef3.value.setRules(rules3.value);

		if (currentIdentity) {
			baseForm.value = {
				...baseForm.value,
				maritalStatus: currentIdentity.maritalStatus,
				educate: currentIdentity.educate,
				province: currentIdentity.province,
				city: currentIdentity.city,
				area: currentIdentity.area,
				residentialAddress: currentIdentity.residentialAddress,
				fullAddress: currentIdentity.fullAddress,
			}
			companyForm.value = {
				...companyForm.value,
				companyName: currentIdentity.companyName,
				workIncome: currentIdentity.workIncome,
				workIndustry: currentIdentity.workIndustry
			}
			if (Array.isArray(currentIdentity.relationships)) {
				contactForm.value = currentIdentity.relationships.map((item) => ({
					fullName: item.fullName,
					mobile: item.mobile,
					relation: item.relation,
				}));
				tagCurrent.value = currentIdentity.relationships[0].relation;
				tagCurrent2.value = currentIdentity.relationships[1].relation;
			}
		}
	})
</script>

<style lang="scss" scoped>
	@import '@/style/style.scss';

	.info_box {
		.info_title {
			.title {
				color: #333333;
				font-weight: bold;
				font-family: PingFang SC;
			}

			.desc {
				color: #666666;
				font-weight: 500;
				font-family: PingFang SC;
			}
		}

		.info_container {
			.base_box {
				min-height: 200rpx;
				box-shadow: 0px 2rpx 12rpx 0px rgba(100, 104, 137, 0.2);
				border-radius: 10rpx;

				.common_top {
					background: #FAE5D1;

					.common_img {
						width: 38rpx;
						height: 38rpx;
					}

					.common_title {
						color: #794D26;
						font-weight: bold;
						font-family: PingFang SC;
					}
				}

				.common_wrap {
					.title {
						color: #2D2E33;
						font-weight: bold;
						font-family: PingFang SC;
					}

					.contact_tag {
						position: relative;
						min-width: 100rpx;
						border-radius: 8rpx;
						border: 2rpx solid #CCCCCC;
						font-weight: 500;
						font-family: PingFang SC;

						&:nth-child(1) {
							margin-left: 0rpx;
						}
					}

					.contact_tag_img {
						width: 20rpx;
						height: 18rpx;
						position: absolute;
						right: 0;
						bottom: 0;
					}

					.active_tag {
						background: #EEF1FF;
						border: 2rpx solid #3C51F2;
					}

					.default {
						color: #a59d9d;
					}
				}
			}

			.company_box {
				@extend.base_box;
			}

			.contact_box {
				@extend.base_box;

				.common_wrap {
					.telephone_directory {
						position: relative;
						border-bottom: 1rpx solid #E6E6E6;

						// #ifdef APP-PLUS
						&::after {
							content: '';
							position: absolute;
							right: 170rpx;
							width: 1rpx;
							height: 120rpx;
							background: #E6E6E6;
							z-index: 1;
						}

						.left {
							width: 76%;
						}

						// #endif
						.select_contacts {
							color: #3C51F2;
							font-weight: 500;
							font-family: PingFang SC;

							.select_book_img {
								width: 38rpx;
								height: 38rpx;
							}
						}

					}
				}
			}

			.next_btn {
				width: 90%;
				color: #FFFFFF;
				background: #3C51F2;
				height: 100rpx;
				font-weight: bold;
				font-family: PingFang SC;
			}

			.back_btn {
				width: 90%;
				height: 94rpx;
				color: #3C51F2;
				border: 1rpx solid #3C51F2;
				font-weight: bold;
				font-family: PingFang SC;
			}
		}

	}
</style>